package org.blog.servlets;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.blog.beans.User;
import org.blog.controller.UserController;
import org.blog.exceptions.InvalidLoginException;
import org.blog.exceptions.InvalidMailException;
import org.blog.exceptions.InvalidPasswordException;
import org.blog.exceptions.LoginAlreadyExistsException;
import org.blog.logic.UserLogic;
import org.blog.messages.LoginMessage;

/**
 * Servlet implementation class Main
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Login() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}
	
	private void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if("logout".equals(request.getParameter("do"))) {
			UserController.logOut(request.getSession());
			getServletContext().getRequestDispatcher("/Main").forward(request, response);
			return;
		}
		
		User user = new User();
		LoginMessage lm = new LoginMessage();
	
		try {
			BeanUtils.populate(user, request.getParameterMap());
			
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		try {
			user = UserLogic.getInstance().login(user);
		} catch (InvalidLoginException e) {
			lm.setMessage("niewlasciwy login lub haslo!");
		} catch (InvalidPasswordException e) {
			lm.setMessage("niewlasciwy login lub haslo!");
		}
		
		if(!lm.error) UserController.logIn(user, request.getSession());
		else request.setAttribute("messageL", lm);
		
		getServletContext().getRequestDispatcher("/Main").forward(request, response);
	}

}
